package com.jprocms.module.cms.content;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.UpdateRequest;
import com.jpro.framework.common.util.collection.MapUtils;
import com.jprocms.module.cms.config.JproProperties;
import com.jprocms.module.cms.convert.content.ContentConvert;
import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.dal.mysql.content.ContentMapper;
import com.jprocms.module.cms.es.convert.EsContentConverter;
import com.jprocms.module.cms.es.dao.EsContentRepo;
import com.jprocms.module.cms.es.dto.ContentEsDto;
import com.jprocms.module.cms.es.po.EsContent;
import com.jprocms.module.cms.es.service.ContentEsService;
import com.jprocms.module.cms.framework.enums.EnumContentEvent;
import com.jprocms.module.cms.service.content.ContentService;
import com.jprocms.module.cms.util.EnvUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * {@link ContentAppEvent} 的监听器
 * 实现内容es同步
 *
 * @author jprocms
 */
@Slf4j
@Component
public class ContentEsSyncListener implements ApplicationListener<ContentAppEvent> {

    @Resource
    private ContentMapper contentMapper;
    @Resource
    private EsContentRepo esContentRepo;
    @Resource
    private JproProperties jproProperties;
    @Resource
    private ContentEsService contentEsService;
    @Resource
    private ElasticsearchClient elasticsearchClient;
    @Value("${elasticsearch.contentIndex}")
    private String contentIndex;
    @Resource
    private ContentService contentService;

    @Override
    public void onApplicationEvent(ContentAppEvent event) {
        if (event.getId() != null) {
            //单条操作
            ContentDO contentDO = contentService.selectByIdIgnoreDel(event.getId());
            if (contentDO == null) {
                return;
            }
            //新建内容不为空则根据栏目配置的采集规则自动推送
            contentEsAsync(event);
        } else {
            //批量删除或者批量发布
            contentEsAsync(event);
        }
    }

    private void contentEsAsync(ContentAppEvent event) {
        if (EnumContentEvent.delete.equals(event.getEvent())) {
            List<Long> ids = event.getIds();
            if (CollectionUtils.isNotEmpty(ids)) {
                esContentRepo.deleteAllById(ids.stream().map(item -> item.toString())
                        .collect(Collectors.toList()));
            }
        } else if (EnumContentEvent.create.equals(event.getEvent()) || EnumContentEvent.update.equals(event.getEvent())) {
            if (CollUtil.isNotEmpty(event.getIds())) {
                for (Long id : event.getIds()) {
                    doUpdateEs(contentService.selectByIdIgnoreDel(id));
                }
            } else {
                doUpdateEs(contentService.selectByIdIgnoreDel(event.getId()));
            }
        }
    }

    private void doUpdateEs(ContentDO contentDO) {
        ContentEsDto contentEsDto = ContentConvert.INSTANCE.convertToEsDtoSimple(contentDO, contentDO.getExt(), contentDO.getCount());
        //根据文档url解析拿到结果设置到docs
        //当前是支持文件搜索功能并且是已发布状态才去解析文档内容
        int productGrade = EnvUtil.getGrade();
        if (productGrade >= 2 && jproProperties.isDocSearchSupport() && contentDO.isPublish()) {
            final List<String> docUrls = contentDO.getDocUrls();
            if (CollUtil.isNotEmpty(docUrls)) {
                List<String> docs = new ArrayList<>();
                for (String docUrl : docUrls) {
                    docs.add(contentEsService.getDocText(docUrl));
                }
                contentEsDto.setDocs(docs);
            }
        }
        EsContent esContent = EsContentConverter.INSTANCE.convert(contentEsDto);
        esContent.setIndexTime(DateUtil.date(LocalDateTimeUtil.now()));
        esContent.setCustoms(MapUtils.filterMapBlank(esContent.getCustoms()));
        final boolean docExist = esContentRepo.existsById(contentDO.getId().toString());
        if (docExist) {
            try {
                update(esContent);
            } catch (IOException e) {
                log.warn("更新索引失败{}", e.getMessage());
                throw new RuntimeException(e);
            }
        } else {
            esContentRepo.save(esContent);
        }
    }

    public void update(EsContent entity) throws IOException {
        if (entity == null) {
            return;
        }
        if (entity.getId() == null) {
            log.warn("更新id为null");
            return;
        }
        UpdateRequest request = new UpdateRequest.Builder<>().index(contentIndex)
                .id(entity.getId()).doc(entity).source(c -> c.fetch(false)).build();
        elasticsearchClient.update(request, EsContent.class);
    }


}
